export default class GameLine {
  constructor(sweeper) {
    this.sweeper = sweeper
    this.init()
  }
  init() {
    if(this.sweeper.settings.autoFlag){
      //如果雷密度过高(>1/3)或雷数过多(>=400)自动关闭
      let difficulty = this.sweeper.difficulty
      if(difficulty.mineNum >= 400 || difficulty.ux*difficulty.uy*difficulty.uz / difficulty.mineNum < 3){
        this.sweeper.settings.autoFlag = false
        this.sweeper._vue.$toast({message:'雷数过多自动插旗已关闭',position:'bottom',duration:'3000'})
      }
    }
    this.timeRunner = 0
    this.gameOver = false
    this.life = 1
    let topList = localStorage['topList']
    if (!topList) {
      this.topList = {
        win: 0,
        lose: 0,
        list: []
      }
    } else {
      this.topList = JSON.parse(topList)
    }
    if (this.beginTime) {
      this.beginTime = null
    }
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
    
  }
  timeStart() {
    if (this.gameOver) {
      return
    }
    let scope = this
    this.beginTime = new Date().getTime()
    this.timer = setInterval(function () {
      scope.timeRunner = parseInt((new Date().getTime() - scope.beginTime) / 10)
    }, 10)
  }
  ifWin() {
    if (this.gameOver) {
      return false
    }
    // const scope = this
    let difficulty = this.sweeper.difficulty
    let counter = this.sweeper.counter
    let group = this.sweeper.threeManager.group
    let numData = this.sweeper.numData
    if (counter.knowNum + counter.mineNum == difficulty.ux * difficulty.uy * difficulty.uz) {
      this.youWin()
      return true
    }
    //如果插完旗判断当前胜负情况
    if (counter.countNum == 0) {
      for (let x = 0; x < difficulty.ux; x++) {
        for (let y = 0; y < difficulty.uy; y++) {
          for (let z = 0; z < difficulty.uz; z++) {
            if (numData[x][y][z] == -1) {
              //该位置的方块是否插旗
              let mesh = group.children[x].children[y].children[z]
              if (!mesh.flag) {
                return false
              }
            }
          }
        }
      }
      //全部符合要求则判胜
      // scope.youWin()
      this.youWin()
      return true
    }
    return false
  }
  youWin() {
    if (this.gameOver) {
      return
    }
    const scope = this
    let difficulty = this.sweeper.difficulty
    let counter = this.sweeper.counter
    let group = this.sweeper.threeManager.group
    let numData = this.sweeper.numData
    let meshCover = this.sweeper.threeManager.meshCover
    this.sweeper.musicCtrl.playGameAudio({ type: 'win' })
    for (let x = 0; x < difficulty.ux; x++) {
      for (let y = 0; y < difficulty.uy; y++) {
        for (let z = 0; z < difficulty.uz; z++) {
          if (numData[x][y][z] == -1) {
            group.children[x].children[y].children[z].material = meshCover.numCovers[0]
          }
        }
      }
    }
    clearInterval(scope.timer)
    counter.countNum = 'WIN'
    this.gameOver = true
    if (this.sweeper.settings.dialog) {
      setTimeout(() => {
        alert('游戏通关,进入菜单页面刷新重新开始游戏!')
      }, 200)
    }
    //存档
    if (this.sweeper.settings.saveScore) {
      let userName = this.sweeper.user.userName
      let topList = this.topList
      //剩余生命，游戏难度，游戏时间，id，name，游戏设置
      let score = {
        userName: userName,
        life: this.life,
        difficulty: difficulty,
        flagSchools: this.sweeper.settings.flagSchools,
        useTime: this.timeRunner,
        dateTime: new Date()
      }
      topList.win++
      if (topList?.['mode' + score.difficulty.mode]?.['d' + score.difficulty.diff]?.['s' + score.flagSchools]) {
        topList['mode' + score.difficulty.mode]['d' + score.difficulty.diff]['s' + score.flagSchools].win++
      } else {
        if (!topList['mode' + score.difficulty.mode]) {
          topList['mode' + score.difficulty.mode] = {}
        }
        if (!topList['mode' + score.difficulty.mode]['d' + score.difficulty.diff]) {
          topList['mode' + score.difficulty.mode]['d' + score.difficulty.diff] = {}
        }
        if (!topList['mode' + score.difficulty.mode]['d' + score.difficulty.diff]['s' + score.flagSchools]) {
          topList['mode' + score.difficulty.mode]['d' + score.difficulty.diff]['s' + score.flagSchools] = {
            win: 1,
            lose: 0
          }
        }
      }
      //将符合条件的按从小到大排序
      let mapList = []
      for (let item of topList.list) {
        if (
          // score.userName == item.userName &&
          score.difficulty.diff == item.difficulty.diff &&
          score.difficulty.mode == item.difficulty.mode &&
          // score.life == item.life &&
          score.flagSchools == item.flagSchools
        ) {
          let insert = false
          for (let index in mapList) {
            if (mapList[index].useTime >= item.useTime) {
              mapList.splice(index, 0, item)
              insert = true
              break
            }
          }
          if (!insert) {
            mapList.push(item)
          }
        }
      }
      //判断本次是否破前十记录
      if (mapList.length < 10) {
        topList.list.push(score)

        this.sweeper._vue.$toast({
          message: '记录保存成功！',
          position: 'bottom',
        });
        localStorage['topList'] = JSON.stringify(topList)
      } else {
        if (mapList[9]?.useTime >= score.useTime) {
          //强制替换，地址不变
          mapList[9].difficulty = score.difficulty
          mapList[9].useTime = score.useTime
          mapList[9].dateTime = score.dateTime

          this.sweeper._vue.$toast({
            message: '记录保存成功！',
            position: 'bottom',
          });
          localStorage['topList'] = JSON.stringify(topList)
        }
      }
    }
  }
  gameLose() {
    if (this.gameOver) {
      return
    }
    if (this.life > 0) {
      this.life--
      return
    }
    const scope = this
    let difficulty = this.sweeper.difficulty
    let counter = this.sweeper.counter
    let group = this.sweeper.threeManager.group
    let numData = this.sweeper.numData
    let meshCover = this.sweeper.threeManager.meshCover

    this.sweeper.musicCtrl.playGameAudio({ type: 'over' })
    for (let x = 0; x < difficulty.ux; x++) {
      for (let y = 0; y < difficulty.uy; y++) {
        for (let z = 0; z < difficulty.uz; z++) {
          if (numData[x][y][z] == -1) {
            group.children[x].children[y].children[z].material = meshCover.numCovers[2]
          }
        }
      }
    }
    clearInterval(scope.timer)
    counter.countNum = 'LOSE'
    this.gameOver = true
    if (this.sweeper.settings.dialog) {
      setTimeout(() => {
        alert('游戏结束,进入菜单页面刷新重新开始游戏!')
      }, 200)
    }
    //统计失败次数
    if (this.sweeper.settings.saveScore) {
      let topList = this.topList
      let flagSchools = this.sweeper.settings.flagSchools
      topList.lose++
      if (topList?.['mode' + difficulty.mode]?.['d' + difficulty.diff]?.['s' + flagSchools]) {
        topList['mode' + difficulty.mode]['d' + difficulty.diff]['s' + flagSchools].lose++
      } else {
        if (!topList['mode' + difficulty.mode]) {
          topList['mode' + difficulty.mode] = {}
        }
        if (!topList['mode' + difficulty.mode]['d' + difficulty.diff]) {
          topList['mode' + difficulty.mode]['d' + difficulty.diff] = {}
        }
        if (!topList['mode' + difficulty.mode]['d' + difficulty.diff]['s' + flagSchools]) {
          topList['mode' + difficulty.mode]['d' + difficulty.diff]['s' + flagSchools] = {
            lose: 1,
            win: 0
          }
        }
      }
      localStorage['topList'] = JSON.stringify(topList)
    }
  }
}
